package com.netforce.util.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public interface IoManager
{
  public long copy(InputStream anInputStream, OutputStream anOutputStream) throws IOException;
  public String toString(InputStream anInputStream) throws IOException;

  public class DefaultIoManager implements IoManager
  {
    @Override
    public long copy(InputStream anInputStream, OutputStream anOutputStream) throws IOException
    {
      long count = 0L;
      byte[] buffer = new byte[BUFFER_SIZE];
      int readed;
      while ((readed = anInputStream.read(buffer, 0, BUFFER_SIZE)) > 0)
      {
        anOutputStream.write(buffer, 0, readed);
        count += readed;
      }
      return count;
    }

    @Override
    public String toString(InputStream anInputStream) throws IOException
    {
      try (InputStream inputStream = anInputStream; ByteArrayOutputStream outputStream = new ByteArrayOutputStream();)
      {
        copy(inputStream, outputStream);
        return new String(outputStream.toByteArray());
      }
    }

    static protected final int BUFFER_SIZE = 1024 * 8;
  }
}
